<?php

include 'vendor/autoload.php';

use Smalot\Cups\Builder\Builder;
use Smalot\Cups\Manager\JobManager;
use Smalot\Cups\Manager\PrinterManager;
use Smalot\Cups\Model\Job;
use Smalot\Cups\Transport\Client;
use Smalot\Cups\Transport\ResponseParser;
use Smalot\Cups\Transport\ImprovedClient;

class ComprehensivePrintTest {
    private $printerIP = '10.1.0.12';
    private $printerPort = 631;
    
    public function runAllTests() {
        echo "=== 综合打印测试 ===\n";
        echo "时间: " . date('Y-m-d H:i:s') . "\n";
        echo "打印机: {$this->printerIP}:{$this->printerPort}\n\n";
        
        // 1. 网络连接测试
        $this->testNetworkConnection();
        
        // 2. IPP协议测试
        $this->testIPPConnection();
        
        // 3. 改进客户端测试
        $this->testImprovedClient();
        
        // 4. Windows系统打印测试
        $this->testWindowsPrint();
        
        echo "\n=== 测试完成 ===\n";
    }
    
    private function testNetworkConnection() {
        echo "🔍 步骤1: 网络连接测试\n";
        echo "----------------------------------------\n";
        
        // Ping测试
        $pingResult = shell_exec("ping -n 1 {$this->printerIP} 2>&1");
        if (strpos($pingResult, 'TTL') !== false) {
            echo "✅ Ping测试: 成功\n";
        } else {
            echo "❌ Ping测试: 失败\n";
            return;
        }
        
        // 端口测试
        $socket = @fsockopen($this->printerIP, $this->printerPort, $errno, $errstr, 5);
        if ($socket) {
            echo "✅ 端口{$this->printerPort}连接: 成功\n";
            fclose($socket);
        } else {
            echo "❌ 端口{$this->printerPort}连接: 失败 - {$errstr}\n";
        }
        
        // HTTP服务测试
        $httpUrl = "http://{$this->printerIP}:{$this->printerPort}/";
        $context = stream_context_create([
            'http' => [
                'timeout' => 5,
                'ignore_errors' => true
            ]
        ]);
        
        $httpResponse = @file_get_contents($httpUrl, false, $context);
        if ($httpResponse !== false) {
            echo "✅ HTTP服务: 可访问\n";
        } else {
            echo "⚠️  HTTP服务: 不可访问\n";
        }
        
        echo "\n";
    }
    
    private function testIPPConnection() {
        echo "🖨️  步骤2: IPP协议测试\n";
        echo "----------------------------------------\n";
        
        try {
            // 使用TCP连接配置
            $socketOptions = [
                'remote_socket' => "tcp://{$this->printerIP}:{$this->printerPort}",
                'timeout' => 10
            ];
            
            $client = new Client(null, null, $socketOptions);
            $builder = new Builder();
            $responseParser = new ResponseParser();
            
            $printerManager = new PrinterManager($builder, $client, $responseParser);
            
            // 尝试查找打印机
            $printerUri = "ipp://{$this->printerIP}:{$this->printerPort}/ipp/print";
            echo "正在查找打印机: {$printerUri}\n";
            
            $printer = $printerManager->findByUri($printerUri);
            echo "✅ IPP打印机查找: 成功\n";
            
            // 尝试创建打印作业
            $this->createAndSendJob($printerManager, $printer);
            
        } catch (Exception $e) {
            echo "❌ IPP连接失败: " . $e->getMessage() . "\n";
            echo "错误类型: " . get_class($e) . "\n";
        }
        
        echo "\n";
    }
    
    private function testImprovedClient() {
        echo "🔧 步骤3: 改进客户端测试\n";
        echo "----------------------------------------\n";
        
        try {
            $improvedClient = ImprovedClient::createForIpAddress($this->printerIP, $this->printerPort);
            $builder = new Builder();
            $responseParser = new ResponseParser();
            
            $printerManager = new PrinterManager($builder, $improvedClient, $responseParser);
            
            $printerUri = "ipp://{$this->printerIP}:{$this->printerPort}/ipp/print";
            echo "正在使用改进客户端查找打印机...\n";
            
            $printer = $printerManager->findByUri($printerUri);
            echo "✅ 改进客户端打印机查找: 成功\n";
            
            // 尝试创建打印作业
            $this->createAndSendJob($printerManager, $printer);
            
        } catch (Exception $e) {
            echo "❌ 改进客户端失败: " . $e->getMessage() . "\n";
        }
        
        echo "\n";
    }
    
    private function createAndSendJob($printerManager, $printer) {
        try {
            $jobManager = new JobManager(
                $printerManager->builder ?? new Builder(),
                $printerManager->client ?? new Client(),
                $printerManager->responseParser ?? new ResponseParser()
            );
            
            $job = new Job();
            $job->setName('综合测试打印作业');
            $job->setUsername('admin');
            $job->setCopies(1);
            $job->setPageRanges('1');
            
            // 创建测试文件
            $testFile = 'comprehensive_test.txt';
            $content = "综合打印测试\n";
            $content .= "时间: " . date('Y-m-d H:i:s') . "\n";
            $content .= "打印机: {$this->printerIP}:{$this->printerPort}\n";
            $content .= "测试类型: IPP协议打印\n";
            
            file_put_contents($testFile, $content);
            
            $job->addFile($testFile);
            $job->addAttribute('media', 'A4');
            $job->addAttribute('fit-to-page', true);
            
            echo "正在发送打印作业...\n";
            $result = $jobManager->send($printer, $job);
            
            echo "✅ 打印作业发送成功!\n";
            echo "作业ID: " . ($result->getId() ?? 'N/A') . "\n";
            
        } catch (Exception $e) {
            echo "❌ 打印作业失败: " . $e->getMessage() . "\n";
        }
    }
    
    private function testWindowsPrint() {
        echo "🖥️  步骤4: Windows系统打印测试\n";
        echo "----------------------------------------\n";
        
        try {
            // 创建测试文件
            $testFile = 'windows_test.txt';
            $content = "Windows系统打印测试\n";
            $content .= "时间: " . date('Y-m-d H:i:s') . "\n";
            $content .= "打印机: {$this->printerIP}:{$this->printerPort}\n";
            $content .= "测试类型: Windows系统打印\n";
            
            file_put_contents($testFile, $content);
            
            // 使用Windows打印命令
            $printCommand = "print /D:\\\\{$this->printerIP}\\ipp {$testFile}";
            echo "执行命令: {$printCommand}\n";
            
            $output = shell_exec($printCommand . ' 2>&1');
            
            if (strpos($output, '正在打印') !== false || strpos($output, 'printing') !== false) {
                echo "✅ Windows系统打印: 成功\n";
            } else {
                echo "⚠️  Windows系统打印: 可能失败\n";
                echo "输出: " . trim($output) . "\n";
                
                // 尝试备用方法
                echo "尝试备用打印方法...\n";
                $altCommand = "notepad /p {$testFile}";
                shell_exec($altCommand);
                echo "✅ 已启动记事本打印\n";
            }
            
        } catch (Exception $e) {
            echo "❌ Windows打印失败: " . $e->getMessage() . "\n";
        }
    }
}

// 运行测试
$test = new ComprehensivePrintTest();
$test->runAllTests();